﻿/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

namespace Daidalos.Patterns
{

    /// <summary>
    ///     A singleton manager. A class can be made a singleton easily 
    ///     by inheriting this class here. For example:
    ///     <example> 
    ///         This sample shows how to inherit from the singleton
    ///         <code>
    ///             class Foo : SingletonManager<Foo> { 
    ///                 public void Bar() {...}
    ///             }
    ///         </code>
    ///     </example>
    ///     And later used by:
    ///     <code>
    ///         Foo.Instance.Bar();
    ///     </code>
    /// </summary>
    /// <typeparam name="T">
    ///     The typename of the templates class used in the recursive 
    ///     template definition.
    /// </typeparam>
    public class SingletonManager<T> where T : class, new()
    {

        #region Properties
        /// <summary>
        ///     Returns the running instance of the template
        /// </summary>
        public static T Instance
        {
            // We'll make the instance readonly, since writing
            // makes no sense at all.
            get
            {
                return SingletonCreator.instance;
            }
        }
        #endregion

        /// <summary>
        ///     A little nested helper class to maintain exactly one running
        ///     instance.
        /// </summary>
        class SingletonCreator
        {

            #region Attributes
            /// <summary>
            ///     Create the new instance.
            /// </summary>
            internal static readonly T instance = new T();
            #endregion

            /// <summary>
            ///     Static initializer.
            /// </summary>
            static SingletonCreator()
            {
            }

        }

    }

}
